package com.boang.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/*
  @author: 13813
  @date: 2024/7/16 14:16
*/
@WebFilter("/*")
public class FilterDemo01 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取项目路径
        String contextPath = request.getContextPath();
        //获取Servlet路径
        String requestURI = request.getRequestURI();
        //Tomcat启动后的跳转index.jsp的请求不拦截           //点击登录页按钮，登录的路径不拦截
        if (requestURI.equals(contextPath + "/") || requestURI.equals(contextPath + "/login")
                || requestURI.equals(contextPath + "/main.jsp")
                || requestURI.equals(contextPath + "/index.jsp")) {
            filterChain.doFilter(servletRequest, servletResponse);//放行
        } else {
            //判断是否登录过
            HttpSession session = request.getSession();
            String username = (String) session.getAttribute("username");

            if (username != null && !username.equals("")) {
                filterChain.doFilter(servletRequest, servletResponse);//放行
            } else {
                response.sendRedirect(contextPath + "/index.jsp");
            }
        }


//

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
